<?php
// The source code packaged with this file is Free Software, Copyright (C) 2005 by
// Ricardo Galli <gallir at uib dot es>.
// It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
// You can get copies of the licenses here:
// 		http://www.affero.org/oagpl.html
// AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".

function get_category_id($cat_name) {
	// find category id when given category name
	// $the_cats is set in /libs/smartyvariables.php
	global $dblang, $the_cats;

	foreach($the_cats as $cat){
		if($cat->category_name == $cat_name && $cat->category_lang == $dblang) { 
			return $cat->category_id; 
		}
	}
	return null;
}

function get_category_name($cat_id) {
	// find category name when given category id
	// $the_cats is set in /libs/smartyvariables.php
	global $dblang, $the_cats;

	foreach($the_cats as $cat){
		if($cat->category_id == $cat_id && $cat->category_lang == $dblang) { 
			return $cat->category_name; 
		}
	}
	return null;
}


function who_voted($storyid, $avatar_size){
	// this returns who voted for a story
	// eventually add support for filters (only show friends, etc)	
	global $db;

	$sql = 'SELECT ' . table_votes . '.*, ' . table_users . '.* FROM ' . table_votes . ' INNER JOIN ' . table_users . ' ON ' . table_votes . '.vote_user_id = ' . table_users . '.user_id WHERE (((' . table_votes . '.vote_value)>0) AND ((' . table_votes . '.vote_link_id)='.$storyid.') AND (' . table_votes . '.vote_type= "links")) AND user_level<>"god";';
	$voters = $db->get_results($sql);
	$voters = object_2_array($voters);
	foreach($voters as $key => $val){
		$voters[$key]['Avatar_ImgSrc'] = get_avatar($avatar_size, "", $val['user_login'], $val['user_email']);
	}

	return $voters;	
}

function who_apply($storyid, $avatar_size){
	
	global $db;

	require_once(mnminclude.'hunt.php');
	$hunt = new Hunt();
	$hunt->linkid = $storyid;
	$hunt->read();
	$huntid = $hunt->id;
	$sql = 'SELECT ' . table_apply . '.*, ' . table_users . '.* FROM ' . table_apply . ' INNER JOIN ' . table_users . ' ON ' . table_apply . '.apply_user_id = ' . table_users . '.user_id WHERE ' . table_apply . '.apply_hunt_id=' . $huntid;
	//die($sql);
	$applies = $db->get_results($sql);
	$applies = object_2_array($applies);
	foreach($applies as $key => $val){
		$applies[$key]['Avatar_ImgSrc'] = get_avatar($avatar_size, "", $val['user_login'], $val['user_email']);
	}

	return $applies;	
}

function related_stories($storyid, $related_tags, $category){
	// this returns similar stories based on tags in common and in the same category    
	global $db;
	$related_tags="'".str_replace(", ","', '",addslashes($related_tags))."'"; // This gives us the proper string structure for IN SQL statement

	// Select 10 stories that share tags with the current story and order them by number of tags they share    
	$sql = "SELECT ".table_links.".link_title, ".table_links.".link_title_url, COUNT( ".table_tags.".tag_link_id ) AS relevance, ".table_tags.".tag_link_id FROM ".table_tags.", ".table_links."    WHERE ".table_tags.".tag_words IN (    ".$related_tags."    ) AND ".table_tags.".tag_link_id = ".table_links.".link_id    AND ".table_links.".link_status != 'discard' AND NOT ".table_links.".link_id = ".$storyid;
	$sql.= " GROUP BY ".table_tags.".tag_link_id, ".table_links.".link_title, ".table_links.".link_title_url ORDER BY relevance DESC LIMIT 10";

	$related_story = $db->get_results($sql);
	$related_story = object_2_array($related_story);
	return $related_story;    
} 

function sanitize($var, $santype = 1){
	if ($santype == 1) {return strip_tags($var);}
	if ($santype == 2) {return htmlentities(strip_tags($var),ENT_QUOTES,'UTF-8');}
	if ($santype == 3) {
		if (!get_magic_quotes_gpc()) {
			return addslashes(htmlentities(strip_tags($var),ENT_QUOTES,'UTF-8'));
		} 
		else {
		   return htmlentities(strip_tags($var),ENT_QUOTES,'UTF-8');
		}
	}
}

function do_we_use_avatars(){
	// checks to see if avatars are enabled
	if(Enable_User_Upload_Avatar == true){return "1";}		
	return "0";
}

function get_avatar($size = "large", $avatarsource, $user_name = "", $user_email = "", $user_id=""){
	// returns the location of a user's avatar
	global $globals;
	
	if($avatarsource == ""){
		include_once(mnminclude.'user.php');
		$user=new User();
		if($user_name != ""){
			$user->username = $user_name;
		} else {
			$user->id = $user_id;
		}
		
		if(!$user->read()) {
			//echo "invalid username or userid in get_avatar";
			//die;
			//if($size == "large"){$imgsize = Avatar_Large;}else{$imgsize = Avatar_Small;}
			
			switch ($size) {
				case "huge":
					$imgsize = Avatar_Huge;
					break;
				case "large":
					$imgsize = Avatar_Large;
					break;
				case "small":
					$imgsize = Avatar_Small;
					break;
				default:
					$imgsize = Avatar_Small;
					break;
			}
			$imgsrc = my_pligg_base . '/avatars' . "/" . "Gravatar_" . $imgsize . ".gif";
			return $imgsrc;
		}else {
			$avatarsource = $user->avatar_source;
			$user_name = $user->username;
			if(isset($user->login)){$user_email = $user->login;}
		}
		$user = "";
	}
	
	//if($size == "large"){$imgsize = Avatar_Large;}else{$imgsize = Avatar_Small;}
	switch ($size) {
				case "huge":
					$imgsize = Avatar_Huge;
					break;
				case "large":
					$imgsize = Avatar_Large;
					break;
				case "small":
					$imgsize = Avatar_Small;
					break;
				default:
					$imgsize = Avatar_Small;
					break;
			}

	// use the user uploaded avatars ?
	if(Enable_User_Upload_Avatar == true && $avatarsource == "useruploaded"){
		$imgsrc = my_pligg_base . User_Upload_Avatar_Folder . "/" . $user_name . "_" . $imgsize . ".jpg";
		return $imgsrc;
	}
			
	if($size == "huge"){return my_base_url . my_pligg_base . Default_Gravatar_Huge;}
	if($size == "large"){return my_base_url . my_pligg_base . Default_Gravatar_Large;}
	if($size == "small"){return my_base_url . my_pligg_base . Default_Gravatar_Small;}
}


function do_sidebar($var_smarty, $navwhere = '') {
	// show the categories in the sidebar
	global $db, $dblang, $globals, $the_cats;
	
	if($navwhere == ''){global $navwhere;}

	// fix for 'undefined index' errors
		if(!isset($navwhere['text4'])){$navwhere['text4'] = '';}else{$navwhere['text4'] = htmlspecialchars($navwhere['text4']);}
		if(!isset($navwhere['text3'])){$navwhere['text3'] = '';}else{$navwhere['text3'] = htmlspecialchars($navwhere['text3']);}
		if(!isset($navwhere['text2'])){$navwhere['text2'] = '';}else{$navwhere['text2'] = htmlspecialchars($navwhere['text2']);}
		if(!isset($navwhere['text1'])){$navwhere['text1'] = '';}else{$navwhere['text1'] = htmlspecialchars($navwhere['text1']);}
		if(!isset($navwhere['link4'])){$navwhere['link4'] = '';}
		if(!isset($navwhere['link3'])){$navwhere['link3'] = '';}
		if(!isset($navwhere['link2'])){$navwhere['link2'] = '';}
		if(!isset($navwhere['link1'])){$navwhere['link1'] = '';}
		$var_smarty->assign('navbar_where', $navwhere);
	
		$var_smarty->assign('body_args', '');	
	// fix for 'undefined index' errors

	$_caching = $var_smarty->cache; 	// get the current cache settings
	$var_smarty->cache = true; 			// cache has to be on otherwise is_cached will always be false
	$var_smarty->cache_lifetime = -1;   // lifetime has to be set to something otherwise is_cached will always be false
	$thetpl = $var_smarty->get_template_vars('the_template_sidebar_modules') . '/categories.tpl';

	// check to see if the category sidebar module is already cached
	// if it is, use it

	if(isset($_REQUEST['category'])){
		$thecat = sanitize($_REQUEST['category'], 3);
	}else{
		$thecat = '';
	}
	if ($var_smarty->is_cached($thetpl, 'sidebar|category|'.$thecat)) {
		$var_smarty->assign('cat_array', 'x'); // this is needed. sidebar.tpl won't include the category module if cat_array doesnt have some data
	}else{
		if(isset($_REQUEST['category'])){
			$thecat = get_cached_category_data('category_safe_name', urlencode(sanitize($_REQUEST['category'], 1)));
			$thecat = $thecat->category_name;
		}
	
		if(!empty($_REQUEST['id'])) {
			$doing_story=true;
		} else {
			$doing_story=false;
		}
	
		$var_smarty->assign('UrlMethod', urlmethod);

		foreach($the_cats as $cat){
			if($cat->category_id == $thecat && $cat->category_lang == $dblang && $cat->category_parent == 0)
			{ 
				$globals['category_id'] = $cat->category_id;
				$globals['category_name'] = $cat->category_name;
			}
		}
	
		$pos = strrpos($_SERVER["SCRIPT_NAME"], "/");
		$script_name = substr($_SERVER["SCRIPT_NAME"], $pos + 1, 100);
		$script_name = str_replace(".php", "", $script_name);
	
		include_once('dbtree.php');
		$array = tree_to_array(0, table_categories);
		$var_smarty->assign('lastspacer', 0);
		$var_smarty->assign('cat_array', $array);		
	
		// use the 'totals' table now 
		$published_count = get_story_count('published');
		
		$var_smarty->assign('published_count', $published_count);
		$sql = "select *,  count(*) as count from " . table_links . ", " . table_categories . " where category_lang='$dblang' and category_id=link_category group by link_category ORDER BY category_name ASC";
		$categorylist = object_2_array($db->get_results($sql));
		$var_smarty->assign('categorylist', $categorylist);
		$var_smarty->assign('category_url', getmyurl('maincategory'));

	}

	$var_smarty->cache = $_caching; // set cache back to original value

	$vars = '';
	check_actions('do_sidebar', $vars);

	return $var_smarty;
}


function force_authentication() {
	// requires user to login before viewing the page
	global $current_user;

	if(!$current_user->authenticated) {
		header("Location: " . getmyurl('login', $_SERVER['REQUEST_URI']));
		die;
	}
	return true;
}

function do_pages($total, $page_size, $thepage, $fetch = false) {
	// "previous" and "next" page buttons
	global $db, $URLMethod, $main_smarty;   
	$index_limit = 10;
	
	$current = get_current_page();
	$total_pages=ceil($total/$page_size);
	$start=max($current-intval($index_limit/2), 1);
	$end=$start+$index_limit-1;

	$output = '';

	if ($URLMethod == 1) {

		$query=preg_replace('/page=[0-9]+/', '', $_SERVER['QUERY_STRING']);
		$query=preg_replace('/^&*(.*)&*$/', "$1", $query);
		if(!empty($query)) $query = "&amp;$query";

		$output .= '<div class="pagination"><p>';

		if($current==1) {
			$output .= '<span>&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous"). '</span>';
		} else {
			$i = $current-1;
			$output .= '<a href="?page='.$i.$query.'">&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous").'</a>';
		}

		if($start>1) {
			$i = 1;
			$output .= '<a href="?page='.$i.$query.'">'.$i.'</a>';
			$output .= '<span>...</span>';
		}
		
		for ($i=$start;$i<=$end && $i<= $total_pages;$i++) {
			if($i==$current) {
				$output .= '<span class="current">'.$i.'</span>';
			} else {
				$output .= '<a href="?page='.$i.$query.'">'.$i.'</a>';
			}
		}
		
		if($total_pages>$end) {
			$i = $total_pages;
			$output .= '<span>...</span>';
			$output .= '<a href="?page='.$i.$query.'">'.$i.'</a>';
		}
		
		if($current<$total_pages) {
			$i = $current+1;
			$output .= '<a href="?page='.$i.$query.'"> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</a>';
		} else {
			$output .= '<span> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</span>';
		}
		$output .= "</p></div>\n";
	}	
	
	if ($URLMethod == 2) {                       

		$query=preg_replace('(login=)', '/', $_SERVER['QUERY_STRING']);	//remove login= from query string //
		$query=preg_replace('(view=)', '', $query);	                    //remove view= from query string //
		$query=preg_replace('(part=)', '', $query);
		$query=preg_replace('(order)', '', $query);	
		$query=preg_replace('/page=[0-9]+/', '', $query);  				//remove page arguments to because its hardcoded in html   //
		$query=preg_replace('/tag=true/', '', $query);  				//remove tag=true in tag query because its handled in .htaccess and hidden for a cleaner look//
		$query=preg_replace('/(.*)=(.*)/', '$1/$2', $query); 	 		//main line to recompose arg to place in url //	
		$query=preg_replace('/&/', '', $query);							//whack any ampersands	//	
		$query=preg_replace('/module\/pagestatistics/', '', $query);
		$query=preg_replace('/search\/(.*)/', 'search=$1', $query);	

		$output .= '<div class="pagination"><p>';

		if($current==1) {
			$output .= '<span>&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous"). '</span>'; } 
		else {
			$i = $current-1;
			if (pagename == "search") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'">&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous").'</a>';
			}
			elseif ($pagename == "admin_users") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'">&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous").'</a>';
			}
			else {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'">&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous").'</a>';
			}
		}

		if($start>1) {
			$i = 1;
			if (pagename == "search") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'">'.$i.'</a>';
			}
			elseif ($pagename == "admin_users") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'">'.$i.'</a>';
			}
			else {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'">'.$i.'</a>';	
			}
			$output .= '<span>...</span>';
		}
		for ($i=$start;$i<=$end && $i<= $total_pages;$i++) {
			if($i==$current) {
				$output .= '<span class="current">'.$i.'</span>';	} 
			else {
				if (pagename == "search") {
					$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'">'.$i.'</a>';
				}
				elseif ($pagename == "admin_users") {
					$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'">'.$i.'</a>';
				}
				else {
					$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'">'.$i.'</a>';
				}
			}	
		}
		
		if($total_pages>$end) {
			$i = $total_pages;
			$output .= '<span>...</span>';
			if (pagename == "search") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'">'.$i.'</a>';
			}
			elseif ($pagename == "admin_users") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'">'.$i.'</a>';
			}
			else {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'">'.$i.'</a>';
			}
		}
		
		if($current<$total_pages) {
			$i = $current+1;
			if (pagename == "search") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'"> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</a>';
			}
			elseif (pagename == "admin_users") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'"> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</a>';
			}
			else {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'"> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</a>'; 
			} 
		}		
		else {
			$output .= '<span> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</span>';	}
		
		$output .= "</p></div>";
	}
	if($fetch == false){
		echo $output;
	} else {
		return $output;
	}
}

function submit_user_do_pages($total, $page_size, $thepage, $fetch = false) {
	// "previous" and "next" page buttons
	global $db, $URLMethod, $main_smarty;   
	$index_limit = 10;
	$current = get_current_page();
	$total_pages=ceil($total/$page_size);
	if ($current > $total_pages) {
		$current = 1;
	}
	$start=max($current-intval($index_limit/2), 1);
	$end=$start+$index_limit-1;

	$output = '';

	//if ($URLMethod == 1) {

		//$query=preg_replace('/page=[0-9]+/', '', $_SERVER['QUERY_STRING']);
		//$query=preg_replace('/^&*(.*)&*$/', "$1", $query);
		//if(!empty($query)) $query = "&amp;$query";

		$output .= '<div class="pagination"><p>';

		if($current==1) {
			//$output .= '<span>&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous"). '</span>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;color:#ccc;margin-right:1px;padding:2px 5px;" value=&#171;' .$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous"). '>' . '</input>';
		} else {
			$i = $current-1;
			//$output .= '<a href="?page='.$i.$query.'">&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous").'</a>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;color:#ccc;margin-right:1px;padding:2px 5px;color:#774525;" onmouseover="this.style.background=' . "'" . '#774525' . "'" . ';' . 'this.style.color=' . "'" . '#fff' . "'" . ';' . '" ' . 'onmouseout="this.style.background=' . "'" . '#fff' . "'" . ';' . 'this.style.color=' . "'" . '#774525' . "'" . ';' . '" ' . 'onclick="this.form.page.value= ' .$i . ' ;this.form.submit()" value=&#171;' .$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous"). '>' . '</input>';
		}

		if($start>1) {
			$i = 1;
			//$output .= '<a href="?page='.$i.$query.'">'.$i.'</a>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#774525;"  onmouseover="this.style.background=' . "'" . '#774525' . "'" . ';' . 'this.style.color=' . "'" . '#fff' . "'" . ';' . '" ' . 'onmouseout="this.style.background=' . "'" . '#fff' . "'" . ';' . 'this.style.color=' . "'" . '#774525' . "'" . ';' . '" ' . 'onclick="this.form.page.value= ' .$i . ' ;this.form.submit()" value=' .$i. '>' . '</input>';
			//$output .= '<span>...</span>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#ccc;" value="...">' . '</input>';
		}
		
		for ($i=$start;$i<=$end && $i<= $total_pages;$i++) {
			if($i==$current) {
				//$output .= '<span class="current">'.$i.'</span>';
				$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#ccc" value=' .$i. '>' . '</input>';
			} else {
				//$output .= '<a href="?page='.$i.$query.'">'.$i.'</a>';
				$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#774525"  onmouseover="this.style.background=' . "'" . '#774525' . "'" . ';' . 'this.style.color=' . "'" . '#fff' . "'" . ';' . '" ' . 'onmouseout="this.style.background=' . "'" . '#fff' . "'" . ';' . 'this.style.color=' . "'" . '#774525' . "'" . ';' . '" ' . 'onclick="this.form.page.value= ' .$i . ' ;this.form.submit()" value=' .$i. '>' . '</input>';
			}
		}
		
		if($total_pages>$end) {
			$i = $total_pages;
			//$output .= '<span>...</span>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#ccc" value="..."> </input>';
			//$output .= '<a href="?page='.$i.$query.'">'.$i.'</a>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#774525"  onmouseover="this.style.background=' . "'" . '#774525' . "'" . ';' . 'this.style.color=' . "'" . '#fff' . "'" . ';' . '" ' . 'onmouseout="this.style.background=' . "'" . '#fff' . "'" . ';' . 'this.style.color=' . "'" . '#774525' . "'" . ';' . '" ' . 'onclick="this.form.page.value= ' .$i . ' ;this.form.submit()" value=' .$i. '>' . '</input>';
		}
		
		if($current<$total_pages) {
			$i = $current+1;
			//$output .= '<a href="?page='.$i.$query.'"> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</a>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#774525"  onmouseover="this.style.background=' . "'" . '#774525' . "'" . ';' . 'this.style.color=' . "'" . '#fff' . "'" . ';' . '" ' . 'onmouseout="this.style.background=' . "'" . '#fff' . "'" . ';' . 'this.style.color=' . "'" . '#774525' . "'" . ';' . '" ' . 'onclick="this.form.page.value= ' .$i . ' ;this.form.submit()" value=' .$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). '&#187;>' . '</input>';
		} else {
			//$output .= '<span> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</span>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#ccc" value=' .$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). '&#187;>' . '</input>';
		}
		//$output .= "</p></div>\n";  //leave the </viv>outside this function ,so other elements can share the style of this div
		$output .= "";
	//}	
	
	/*if ($URLMethod == 2) {                       

		$query=preg_replace('(login=)', '/', $_SERVER['QUERY_STRING']);	//remove login= from query string //
		$query=preg_replace('(view=)', '', $query);	                    //remove view= from query string //
		$query=preg_replace('(part=)', '', $query);
		$query=preg_replace('(order)', '', $query);	
		$query=preg_replace('/page=[0-9]+/', '', $query);  				//remove page arguments to because its hardcoded in html   //
		$query=preg_replace('/tag=true/', '', $query);  				//remove tag=true in tag query because its handled in .htaccess and hidden for a cleaner look//
		$query=preg_replace('/(.*)=(.*)/', '$1/$2', $query); 	 		//main line to recompose arg to place in url //	
		$query=preg_replace('/&/', '', $query);							//whack any ampersands	//	
		$query=preg_replace('/module\/pagestatistics/', '', $query);
		$query=preg_replace('/search\/(.*)/', 'search=$1', $query);	

		$output .= '<div class="pagination"><p>';

		if($current==1) {
			$output .= '<span>&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous"). '</span>'; } 
		else {
			$i = $current-1;
			if (pagename == "search") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'">&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous").'</a>';
			}
			elseif ($pagename == "admin_users") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'">&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous").'</a>';
			}
			else {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'">&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous").'</a>';
			}
		}

		if($start>1) {
			$i = 1;
			if (pagename == "search") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'">'.$i.'</a>';
			}
			elseif ($pagename == "admin_users") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'">'.$i.'</a>';
			}
			else {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'">'.$i.'</a>';	
			}
			$output .= '<span>...</span>';
		}
		for ($i=$start;$i<=$end && $i<= $total_pages;$i++) {
			if($i==$current) {
				$output .= '<span class="current">'.$i.'</span>';	} 
			else {
				if (pagename == "search") {
					$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'">'.$i.'</a>';
				}
				elseif ($pagename == "admin_users") {
					$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'">'.$i.'</a>';
				}
				else {
					$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'">'.$i.'</a>';
				}
			}	
		}
		
		if($total_pages>$end) {
			$i = $total_pages;
			$output .= '<span>...</span>';
			if (pagename == "search") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'">'.$i.'</a>';
			}
			elseif ($pagename == "admin_users") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'">'.$i.'</a>';
			}
			else {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'">'.$i.'</a>';
			}
		}
		
		if($current<$total_pages) {
			$i = $current+1;
			if (pagename == "search") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'"> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</a>';
			}
			elseif (pagename == "admin_users") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'"> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</a>';
			}
			else {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'"> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</a>'; 
			} 
		}		
		else {
			$output .= '<span> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</span>';	}
		
		$output .= "</p></div>";
	}*/
	if($fetch == false){
		echo $output;
	} else {
		return $output;
	}
}

function reco_do_pages($total, $page_size, $thepage, $fetch = false) {
	// "previous" and "next" page buttons
	global $db, $URLMethod, $main_smarty;   
	$index_limit = 10;
	
	$current = reco_get_current_page();
	$total_pages=ceil($total/$page_size);
	$start=max($current-intval($index_limit/2), 1);
	$end=$start+$index_limit-1;

	$output = '';

	//if ($URLMethod == 1) {

		//$query=preg_replace('/page=[0-9]+/', '', $_SERVER['QUERY_STRING']);
		//$query=preg_replace('/^&*(.*)&*$/', "$1", $query);
		//if(!empty($query)) $query = "&amp;$query";

		$output .= '<div class="pagination"><p>';

		if($current==1) {
			//$output .= '<span>&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous"). '</span>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;color:#ccc;margin-right:1px;padding:2px 5px;" value=&#171;' .$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous"). '>' . '</input>';
		} else {
			$i = $current-1;
			//$output .= '<a href="?page='.$i.$query.'">&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous").'</a>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;color:#ccc;margin-right:1px;padding:2px 5px;color:#774525;" onmouseover="this.style.background=' . "'" . '#774525' . "'" . ';' . 'this.style.color=' . "'" . '#fff' . "'" . ';' . '" ' . 'onmouseout="this.style.background=' . "'" . '#fff' . "'" . ';' . 'this.style.color=' . "'" . '#774525' . "'" . ';' . '" ' . 'onclick="this.form.reco_page.value= ' .$i . ' ;this.form.submit()" value=&#171;' .$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous"). '>' . '</input>';
		}

		if($start>1) {
			$i = 1;
			//$output .= '<a href="?page='.$i.$query.'">'.$i.'</a>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#774525;"  onmouseover="this.style.background=' . "'" . '#774525' . "'" . ';' . 'this.style.color=' . "'" . '#fff' . "'" . ';' . '" ' . 'onmouseout="this.style.background=' . "'" . '#fff' . "'" . ';' . 'this.style.color=' . "'" . '#774525' . "'" . ';' . '" ' . 'onclick="this.form.reco_page.value= ' .$i . ' ;this.form.submit()" value=' .$i. '>' . '</input>';
			//$output .= '<span>...</span>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#ccc;" value="...">' . '</input>';
		}
		
		for ($i=$start;$i<=$end && $i<= $total_pages;$i++) {
			if($i==$current) {
				//$output .= '<span class="current">'.$i.'</span>';
				$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#ccc" value=' .$i. '>' . '</input>';
			} else {
				//$output .= '<a href="?page='.$i.$query.'">'.$i.'</a>';
				$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#774525"  onmouseover="this.style.background=' . "'" . '#774525' . "'" . ';' . 'this.style.color=' . "'" . '#fff' . "'" . ';' . '" ' . 'onmouseout="this.style.background=' . "'" . '#fff' . "'" . ';' . 'this.style.color=' . "'" . '#774525' . "'" . ';' . '" ' . 'onclick="this.form.reco_page.value= ' .$i . ' ;this.form.submit()" value=' .$i. '>' . '</input>';
			}
		}
		
		if($total_pages>$end) {
			$i = $total_pages;
			//$output .= '<span>...</span>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#ccc" value="..."> </input>';
			//$output .= '<a href="?page='.$i.$query.'">'.$i.'</a>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#774525"  onmouseover="this.style.background=' . "'" . '#774525' . "'" . ';' . 'this.style.color=' . "'" . '#fff' . "'" . ';' . '" ' . 'onmouseout="this.style.background=' . "'" . '#fff' . "'" . ';' . 'this.style.color=' . "'" . '#774525' . "'" . ';' . '" ' . 'onclick="this.form.reco_page.value= ' .$i . ' ;this.form.submit()" value=' .$i. '>' . '</input>';
		}
		
		if($current<$total_pages) {
			$i = $current+1;
			//$output .= '<a href="?page='.$i.$query.'"> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</a>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#774525"  onmouseover="this.style.background=' . "'" . '#774525' . "'" . ';' . 'this.style.color=' . "'" . '#fff' . "'" . ';' . '" ' . 'onmouseout="this.style.background=' . "'" . '#fff' . "'" . ';' . 'this.style.color=' . "'" . '#774525' . "'" . ';' . '" ' . 'onclick="this.form.reco_page.value= ' .$i . ' ;this.form.submit()" value=' .$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). '&#187;>' . '</input>';
		} else {
			//$output .= '<span> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</span>';
			$output .= '<input type="button" style="text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;color:#ccc" value=' .$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). '&#187;>' . '</input>';
		}
		//$output .= "</p></div>\n";  //leave the </viv>outside this function ,so other elements can share the style of this div
		$output .= "";
	//}	
	
	/*if ($URLMethod == 2) {                       

		$query=preg_replace('(login=)', '/', $_SERVER['QUERY_STRING']);	//remove login= from query string //
		$query=preg_replace('(view=)', '', $query);	                    //remove view= from query string //
		$query=preg_replace('(part=)', '', $query);
		$query=preg_replace('(order)', '', $query);	
		$query=preg_replace('/page=[0-9]+/', '', $query);  				//remove page arguments to because its hardcoded in html   //
		$query=preg_replace('/tag=true/', '', $query);  				//remove tag=true in tag query because its handled in .htaccess and hidden for a cleaner look//
		$query=preg_replace('/(.*)=(.*)/', '$1/$2', $query); 	 		//main line to recompose arg to place in url //	
		$query=preg_replace('/&/', '', $query);							//whack any ampersands	//	
		$query=preg_replace('/module\/pagestatistics/', '', $query);
		$query=preg_replace('/search\/(.*)/', 'search=$1', $query);	

		$output .= '<div class="pagination"><p>';

		if($current==1) {
			$output .= '<span>&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous"). '</span>'; } 
		else {
			$i = $current-1;
			if (pagename == "search") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'">&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous").'</a>';
			}
			elseif ($pagename == "admin_users") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'">&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous").'</a>';
			}
			else {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'">&#171; '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Previous").'</a>';
			}
		}

		if($start>1) {
			$i = 1;
			if (pagename == "search") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'">'.$i.'</a>';
			}
			elseif ($pagename == "admin_users") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'">'.$i.'</a>';
			}
			else {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'">'.$i.'</a>';	
			}
			$output .= '<span>...</span>';
		}
		for ($i=$start;$i<=$end && $i<= $total_pages;$i++) {
			if($i==$current) {
				$output .= '<span class="current">'.$i.'</span>';	} 
			else {
				if (pagename == "search") {
					$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'">'.$i.'</a>';
				}
				elseif ($pagename == "admin_users") {
					$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'">'.$i.'</a>';
				}
				else {
					$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'">'.$i.'</a>';
				}
			}	
		}
		
		if($total_pages>$end) {
			$i = $total_pages;
			$output .= '<span>...</span>';
			if (pagename == "search") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'">'.$i.'</a>';
			}
			elseif ($pagename == "admin_users") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'">'.$i.'</a>';
			}
			else {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'">'.$i.'</a>';
			}
		}
		
		if($current<$total_pages) {
			$i = $current+1;
			if (pagename == "search") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'&'.$query.'"> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</a>';
			}
			elseif (pagename == "admin_users") {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'.php?page='.$i.'"> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</a>';
			}
			else {
				$output .= '<a href="'.my_pligg_base.'/'.pagename.'/page/'.$i.'/'.$query.'"> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</a>'; 
			} 
		}		
		else {
			$output .= '<span> '.$main_smarty->get_config_vars("PLIGG_Visual_Page_Next"). ' &#187;' . '</span>';	}
		
		$output .= "</p></div>";
	}*/
	if($fetch == false){
		echo $output;
	} else {
		return $output;
	}
}

function generateHash($plainText, $salt = null){
    if ($salt === null) {
        $salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH); }
    else {
        $salt = substr($salt, 0, SALT_LENGTH); 
	}		
    return $salt . sha1($salt . $plainText);
}

function getmyFullurl($x, $var1="", $var2="", $var3="") {
	return my_base_url . getmyurl($x, $var1, $var2, $var3);
}

function getmyurl($x, $var1="", $var2="", $var3="") {
	global $URLMethod;
	
	If ($x == "storyURL") {
		// var 1 = category_safe_name
		// var 2 = title_url
		// var 3 = story id
		if(enable_friendly_urls == true){
		    if(enable_friendly_caturls == true){
					return getmyurl("storycattitle", $var1, $var2);
		    } else {
					return getmyurl("storytitle", $var2);
		    }
		} else {
			return getmyurl("story", $var3);
		}
	}
	
	
	if ($URLMethod == 1) {
	
		If ($x == "maincategory") {return my_pligg_base."/index.php?category=" . $var1;}
		If ($x == "queuedcategory") {return my_pligg_base."/upcoming.php?category=" . $var1;}
		If ($x == "discardedcategory") {return my_pligg_base."/discarded.php?category=" . $var1;}
		If ($x == "editlink") {return my_pligg_base."/editlink.php?id=" . $var1;}
		If ($x == "edit") {return my_pligg_base."/edit.php?id=" . $var1 . "&amp;commentid=" . $var2;}
		If ($x == "user") {return my_pligg_base."/user.php?login=" . $var1;}
		If ($x == "user_inbox") {return my_pligg_base."/user.php?view=" . $var1;}
		If ($x == "user_add_remove") {return my_pligg_base."/user.php?login=" . $var1. "&amp;view=" . $var2;}
		If ($x == "user_add_links") {return my_pligg_base."/user_add_remove_links.php?action=add&amp;link=" . $var1;}
		If ($x == "user_remove_links") {return my_pligg_base."/user_add_remove_links.php?action=remove&amp;link=" . $var1;}
		If ($x == "user_friends") {return my_pligg_base."/user.php?login=" . $var1. "&amp;view=" . $var2;}
		If ($x == "index_sort") {return my_pligg_base."/index.php?part=".$var1.$var2;}
		If ($x == "userblank") {return my_pligg_base."/user.php?login=";}
		If ($x == "user2") {return my_pligg_base."/user.php?login=".$var1."&amp;view=".$var2;}
		If ($x == "search") {return my_pligg_base."/search.php?search=" . $var1;}
		If ($x == "search_url") {return my_pligg_base."/search.php?url=" . $var1;}
		If ($x == "login") {return my_pligg_base."/login.php?return=" . $var1;}
		If ($x == "logout") {return my_pligg_base."/login.php?op=logout&return=" . $var1;}
		If ($x == "register") {return my_pligg_base."/register.php";}
		If ($x == "category") {return my_pligg_base."/index.php?category=" . $var1;}
		If ($x == "submit") {return my_pligg_base."/submit.php";}
		If ($x == "story") {return my_pligg_base."/story.php?id=" . $var1;}
		If ($x == "storytitle") {return my_pligg_base."/story.php?title=" . $var1;}
		If ($x == "storycattitle") {return my_pligg_base."/story.php?title=" . $var2;}
		If ($x == "out") {return my_pligg_base."/out.php?id=" . $var1;}
		If ($x == "outtitle") {return my_pligg_base."/out.php?title=" . $var1;}
		If ($x == "outurl") {return my_pligg_base."/out.php?url=" . rawurlencode($var1);}
		If ($x == "root") {return my_pligg_base."/index.php";}
		If ($x == "upcoming") {return my_pligg_base."/upcoming.php";}
		If ($x == "upcoming_sort") {return my_pligg_base."/upcoming.php?part=upcoming&amp;order=".$var1.$var2;}
		If ($x == "discarded") {return my_pligg_base."/discarded.php";}
		If ($x == "topusers") {return my_pligg_base."/topusers.php";}
		If ($x == "profile") {return my_pligg_base."/profile.php";}
		If ($x == "userNoVar") {return my_pligg_base."/user.php";}
		If ($x == "loginNoVar") {return my_pligg_base."/login.php";}
		If ($x == "rssTime") {return my_pligg_base."/rss.php?time=" . $var1;}
		If ($x == "about") {return my_pligg_base."/faq-".$var1.".php";}
		If ($x == "bugreport") {return my_pligg_base."/bugreport.php";}
		If ($x == "rss") {return my_pligg_base."/rss.php";}
		If ($x == "rssqueued") {return my_pligg_base."/rss.php?status=queued";}
		If ($x == "rssall") {return my_pligg_base."/rss.php?status=all";}
		If ($x == "rsscategory") {return my_pligg_base."/rss.php?category=". $var1;}
		If ($x == "rsssearch") {return my_pligg_base."/rss.php?search=". $var1;}
		If ($x == "rssuser") {return my_pligg_base."/userrss.php?user=". $var1. "&amp;status=" . $var2;}
		If ($x == "trackback") {return my_pligg_base."/trackback.php?id=" . $var1;}
		If ($x == "page") {return my_pligg_base."/?page=";}
		If ($x == "upcoming_cat") {return my_pligg_base."/?category=";}
		If ($x == "discarded_cat") {return my_pligg_base."/?category=";}
		If ($x == "admin") {return my_pligg_base."/admin_index.php";}
		If ($x == "admin_modify") {return my_pligg_base."/linkadmin.php?id=" . $var1 . "&amp;action=main";}
		If ($x == "admin_modify_do") {return my_pligg_base."/linkadmin.php?id=" . $var1 . "&amp;action=do" . $var2;}
		If ($x == "admin_modify_edo") {return my_pligg_base."/linkadmin.php?id=" . $var1 . "&amp;action=edo" . $var2;}
		If ($x == "admin_discard") {return my_pligg_base."/linkadmin.php?id=" . $var1 . "&amp;action=discard";}
		If ($x == "admin_queued") {return my_pligg_base."/linkadmin.php?id=" . $var1 . "&amp;action=queued";}
		If ($x == "admin_published") {return my_pligg_base."/linkadmin.php?id=" . $var1 . "&amp;action=published";}
		If ($x == "editcomment") {return my_pligg_base."/edit.php?id=" . $var2 . "&amp;commentid=" . $var1;}
		If ($x == "tagcloud") {return my_pligg_base."/cloud.php";}
		If ($x == "tagcloud_range") {return my_pligg_base."/cloud.php?range=" . $var1;}
		If ($x == "comments") {return my_pligg_base."/live_comments.php";}
		If ($x == "published") {return my_pligg_base."/live_published.php";}
		If ($x == "unpublished") {return my_pligg_base."/live_unpublished.php";}
		If ($x == "tag") {return my_pligg_base."/search.php?search=" . $var1 . "&amp;tag=true";}
		If ($x == "tag2") {return my_pligg_base."/search.php?search=" . $var1 . "&amp;tag=true&amp;from=" . $var2;}
		If ($x == "live") {return my_pligg_base."/live.php";}
		If ($x == "template") {return my_pligg_base."/settemplate.php";}
		If ($x == "settemplate") {return my_pligg_base."/settemplate.php?template=" .$var1;}
	}
	if ($URLMethod == 2) { 
	
		If ($x == "maincategory") {return my_pligg_base."/category/" . $var1;}
		If ($x == "queuedcategory") {return my_pligg_base."/upcoming/category/" . $var1;}
		If ($x == "discardedcategory") {return my_pligg_base."/discarded/category/" . $var1;}
		If ($x == "editlink") {return my_pligg_base."/story/" . $var1 . "/edit/";}
		If ($x == "edit") {return my_pligg_base."/story/" . $var1 . "/editcomment/" . $var2;}
		If ($x == "user") {return my_pligg_base."/user/view/profile/" . $var1;}
		If ($x == "user_friends") {return my_pligg_base."/user/view/" . $var2;}
		If ($x == "user_add_remove") {return my_pligg_base."/user/view/" . $var2. "/login/" . $var1;}
		If ($x == "user_add_links") {return my_pligg_base."/user/add/link/" . $var1;}
		If ($x == "user_remove_links") {return my_pligg_base."/user/remove/link/" . $var1;}
		If ($x == "user_inbox") {return my_pligg_base."/inbox";}
		If ($x == "userblank") {return my_pligg_base."/user/";}
		If ($x == "user2") {return my_pligg_base."/user/view/" . $var2 . "/login/" . $var1;}
		If ($x == "index") {return my_pligg_base."/published/";}
		If ($x == "index_sort") {return my_pligg_base."/published/" . $var1 . "/".$var2;}
		If ($x == "search") {return my_pligg_base."/search/" . $var1;}
		If ($x == "search_url") {return my_pligg_base."/searchurl/" . $var1;}
		If ($x == "login") {return my_pligg_base."/login.php?return=" . $var1;}
		If ($x == "logout") {return my_pligg_base."/login.php?op=logout&return=" . $var1;}
		If ($x == "register") {return my_pligg_base."/register";}
		If ($x == "submit") {return my_pligg_base."/submit";}
		If ($x == "story") {return my_pligg_base."/story/" . $var1;}
		If ($x == "storytitle") {return my_pligg_base."/story/title/" . $var1;}
		If ($x == "storycattitle") {return my_pligg_base."/" . $var1 . "/" . $var2 ."/";}
		If ($x == "out") {return my_pligg_base."/out/" . $var1 . "/";}
		If ($x == "outtitle") {return my_pligg_base."/out/" . $var1;}
		If ($x == "root") {return my_pligg_base."/";}
		If ($x == "upcoming") {return my_pligg_base."/upcoming";}
		If ($x == "upcoming_sort") {return my_pligg_base."/upcoming/" .$var1."/".$var2;}
		If ($x == "topusers") {return my_pligg_base."/topusers";}
		If ($x == "profile") {return my_pligg_base."/profile";}
		If ($x == "userNoVar") {return my_pligg_base."/user";}
		If ($x == "loginNoVar") {return my_pligg_base."/login";}
		If ($x == "rssTime") {return my_pligg_base."/rss.php?time=" . $var1;}
		If ($x == "about") {return my_pligg_base."/about/".$var1;}
		If ($x == "rss") {return my_pligg_base."/rss";}
		If ($x == "rssuser") {return my_pligg_base."/rss/user/" . $var1 . "/";}
		If ($x == "rssqueued") {return my_pligg_base."/rss/" . $var1;}
		If ($x == "rssall") {return my_pligg_base."/rss/" . $var1;}
		If ($x == "rsscategory") {return my_pligg_base."/rss/category/" . $var1;}
		If ($x == "rsssearch") {return my_pligg_base."/rss/search" . $var1 . "/";}
		If ($x == "page") {return my_pligg_base."?page=";}
		If ($x == "editcomment") {return my_pligg_base."/story/" . $var2 . "/editcomment/" . $var1;} //leave the . in "./editcomment" because full url should be /story/15/editcomment/2
		If ($x == "tagcloud") {return my_pligg_base."/tagcloud";}
		If ($x == "tagcloud_range") {return my_pligg_base."/tagcloud/range/" . $var1;}
		If ($x == "comments") {return my_pligg_base."/comments";}
		If ($x == "published") {return my_pligg_base."/live_published";}
		If ($x == "unpublished") {return my_pligg_base."/unpublished";}
		If ($x == "tag") {return my_pligg_base."/tag/" . $var1;}
		If ($x == "tag2") {return my_pligg_base."/tag/" . $var1 . "/" . $var2 . "/";}
		If ($x == "live") {return my_pligg_base."/live";}
		If ($x == "template") {return my_pligg_base."/settemplate";}
		If ($x == "settemplate") {return my_pligg_base."/settemplate/" .$var1;}
		If ($x == "admin") {return my_pligg_base."/admin";}
		If ($x == "admin_modify") {return my_pligg_base."/story/" . $var1 . "/modify/main/";}
		If ($x == "admin_modify_do") {return my_pligg_base."/story/" . $var1 . "/modify/do" . $var2 . "/";}
		If ($x == "admin_modify_edo") {return my_pligg_base."/story/" . $var1 . "/modify/edo" . $var2 . "/";}
		If ($x == "admin_discard") {return my_pligg_base."/story/" . $var1 . "/modify/discard/";}
		If ($x == "admin_queued") {return my_pligg_base."/story/" . $var1 . "/modify/queued/";}
		If ($x == "admin_published") {return my_pligg_base."/story/" . $var1 . "/modify/published/";}
	}
}

function SetSmartyURLs($main_smarty) {
	global $dblang;
	if(strpos($_SERVER['PHP_SELF'], "login.php") === false){
		$main_smarty->assign('URL_login', htmlentities(getmyurl("login", $_SERVER['REQUEST_URI'])));
	} else{
		$main_smarty->assign('URL_login', getmyurl("loginNoVar"));
	}
	$main_smarty->assign('URL_logout', htmlentities(getmyurl("logout", $_SERVER['REQUEST_URI'])));
	$main_smarty->assign('URL_register', getmyurl("register"));
	$main_smarty->assign('URL_root', getmyurl("root"));
	$main_smarty->assign('URL_index', getmyurl("index"));
	$main_smarty->assign('URL_search', getmyurl("search"));
	$main_smarty->assign('URL_maincategory', getmyurl("maincategory"));
	$main_smarty->assign('URL_queuedcategory', getmyurl("queuedcategory"));
	$main_smarty->assign('URL_category', getmyurl("category"));
	$main_smarty->assign('URL_user', getmyurl("user"));
	$main_smarty->assign('URL_userNoVar', getmyurl("userNoVar"));
	$main_smarty->assign('URL_user_inbox', getmyurl("user_inbox", "inbox"));
	$main_smarty->assign('URL_user_add_remove', getmyurl("user_add_remove"));
	$main_smarty->assign('URL_profile', getmyurl("profile"));
	$main_smarty->assign('URL_story', getmyurl("story"));
	$main_smarty->assign('URL_storytitle', getmyurl("storytitle"));
	$main_smarty->assign('URL_topusers', getmyurl("topusers"));
	$main_smarty->assign('URL_about', getmyurl("about", $dblang));
	$main_smarty->assign('URL_upcoming', getmyurl("upcoming"));
	$main_smarty->assign('URL_submit', getmyurl("submit"));
	$main_smarty->assign('URL_submit_thing', getmyurl("submit_thing"));
	$main_smarty->assign('URL_submit_user', getmyurl("submit_user"));
	$main_smarty->assign('URL_rss', getmyurl("rss"));
	$main_smarty->assign('URL_rsscategory', getmyurl("rsscategory"));
	$main_smarty->assign('URL_rssqueued', getmyurl("rssqueued", "queued"));
	$main_smarty->assign('URL_rssall', getmyurl("rssall", "all"));
	$main_smarty->assign('URL_rsssearch', getmyurl("rsssearch"));
	$main_smarty->assign('URL_admin', getmyurl("admin"));
	$main_smarty->assign('URL_admin_users', getmyurl("admin_users"));
	$main_smarty->assign('URL_admin_language', getmyurl("admin_language"));
	$main_smarty->assign('URL_admin_categories', getmyurl("admin_categories"));
	$main_smarty->assign('URL_admin_backup', getmyurl("admin_backup"));
	$main_smarty->assign('URL_admin_modules', getmyurl("admin_modules"));
	$main_smarty->assign('URL_admin_config', getmyurl("admin_config"));
	$main_smarty->assign('URL_admin_rss', getmyurl("admin_rss"));
	$main_smarty->assign('URL_tagcloud', getmyurl("tagcloud"));
	$main_smarty->assign('URL_tagcloud_range', getmyurl("tagcloud_range"));
	$main_smarty->assign('URL_live', getmyurl("live"));
	$main_smarty->assign('URL_unpublished', getmyurl("unpublished"));
	$main_smarty->assign('URL_published', getmyurl("published"));
	$main_smarty->assign('URL_comments', getmyurl("comments"));
	$main_smarty->assign('URL_template', getmyurl("template"));
	$main_smarty->assign('URL_settemplate', getmyurl("settemplate"));
	return $main_smarty;
}

function friend_MD5($userA, $userB) {
	include_once(mnminclude.'user.php');
	$user=new User();
	$user->username = $userA;
	if(!$user->read()) {
		echo "a-" . $userA . "error 2";
		die;
	}
	$userAdata = $user->username . $user->date;

	$user=new User();
	$user->username = $userB;
	if(!$user->read()) {
		echo "b-" . $userB . "error 2";
		die;
	}
	$userBdata = $user->username . $user->date;

	$themd5 = md5($userAdata . $userBdata);
	return $themd5;
}

function totals_regenerate(){
	global $db, $cached_totals;
	
	$name = 'queued';
	$count = $db->get_var("SELECT count(*) FROM " . table_links . " WHERE link_status='$name';");
	$db->query("UPDATE `" . table_totals . "` set `total` = $count where `name` = '$name';");	
	$cached_totals[$name] = $count;

	$name = 'published';
	$count = $db->get_var("SELECT count(*) FROM " . table_links . " WHERE link_status='$name';");
	$db->query("UPDATE `" . table_totals . "` set `total` = $count where `name` = '$name';");	
	$cached_totals[$name] = $count;

	if(caching == 1){
		// this is to clear the cache and reload it for settings_from_db.php
		$db->cache_dir = mnmpath.'cache';
		$db->use_disk_cache = true;
		$db->cache_queries = true;
		$db->cache_timeout = 0;
		$totals = $db->get_results("SELECT * FROM `" . table_totals . "`");
		$db->cache_queries = false;
	}

	return true;
}

function totals_adjust_count($name, $adjust){
	global $db, $cached_totals;

	$db->query('UPDATE '.table_totals.' SET total=total+'.$adjust.' WHERE name="'.$name.'"');
	$cached_totals[$name] = $db->get_var('SELECT total FROM '.table_totals.' WHERE name="'.$name.'"');

	if(caching == 1){
		// this is to clear the cache and reload it for settings_from_db.php
		$db->cache_dir = mnmpath.'cache';
		$db->use_disk_cache = true;
		$db->cache_queries = true;
		$db->cache_timeout = 0;
		$totals = $db->get_results("SELECT * FROM `" . table_totals . "`");
		$db->cache_queries = false;
	}
	
	return true;
}

function get_story_count($name){
	global $db, $cached_totals;

	if(summarize_mysql == 1){
		if(isset($cached_totals[$name])){
			return $cached_totals[$name];
		} else {
			
			if(caching == 1){
				$db->cache_dir = mnmpath.'cache';
				$db->use_disk_cache = true;
				$db->cache_queries = true;
			}
			
			$totals = $db->get_results("SELECT * FROM `" . table_totals . "`");

			$db->cache_queries = false;

			foreach ($totals as $total) {
				$cached_totals[$total->name] = $total->total;
			}
			return $cached_totals[$name];
		}
	}else{	
		return $db->get_var("SELECT count(*) FROM " . table_links . " WHERE link_status='$name';");
	}
}

function user_digged($user_login,$user_id){
		include_once(mnminclude.'user.php');
		include_once(mnminclude.'link.php');
		$user=new User();
		$digglink = new Link();
		global $db,$my_base_url,$my_pligg_base;
		$digger = array();
		$digged=false;
		$digger_id=0;
		$digger_login='';
		$digger_names='';
		$digger_digglinkid = '';
		$digger_digglinkvotes = 0;
		$digger_digglinkcomments = 0;
		$sql = "SELECT  *  FROM " . table_links . " WHERE ((link_status='published') OR (link_status='queued')) AND (link_url = '". $my_base_url. $my_pligg_base. "/user.php?login=".$user_login . "')";
		if($digg_info = $db->get_row($sql)){
			$digged=true;
			$digger_id = $digg_info->link_author;
			$digger_digglinkid = $digg_info->link_id;
			$digglink->id = $digg_info->link_id;
			$digglink->read();
			$digger_digglinkvotes = $digglink->count_all_votes(">0");
			$digger_digglinkcomments = $digglink->comments;
			$user->id = $digger_id;
			$user->read();
			$digger_login = $user->username;
			$digger_names = $user->names;
		}
		else {
			$sql = "SELECT  *  FROM " . table_links . " WHERE ((link_status='published') OR (link_status='queued')) AND (link_url = '". $my_base_url. $my_pligg_base. "/user.php?uid=".$user_id . "')";
			if($digg_info = $db->get_row($sql)){
				$digged=true;
				$digger_id = $digg_info->link_author;
				$digger_digglinkid = $digg_info->link_id;
				$digglink->id = $digg_info->link_id;
				$digglink->read();
				$digger_digglinkvotes = $digglink->count_all_votes(">0");
				$digger_digglinkcomments = $digglink->comments;
				$user->id = $digger_id;
				$user->read();
				$digger_login = $user->username;
				$digger_names = $user->names;
			}
			else {
				$digged=false;
			}
		}
		$digger['digged'] = $digged;
		$digger['digger_id'] = $digger_id;
		$digger['digger_login'] = $digger_login;
		$digger['digger_names'] = $digger_names;
		$digger['digger_digglinkid'] = $digger_digglinkid;
		$digger['digger_digglinkvotes'] = $digger_digglinkvotes;
		$digger['digger_digglinkcomments'] = $digger_digglinkcomments;
		return $digger;
	}

function check_url ($urltocheck) {
	if (($urltocheck == '')||($urltocheck == 'http://')) {
		return false;
	}
	require_once(mnminclude.'link.php');
	$link = new Link();	
	$link->get($urltocheck);
	return $link->valid;
}

function get_trackback_from_url($url) {
	if (($url == '')||($url == 'http://')) {
		return '';
	}
	require_once(mnminclude.'link.php');
	$link = new Link();	
	$link->get($url);
	if (!$link->valid) {
		return '';
	}
	else {
		if ($link->trackback == '') {
			return '';
		}
		else {
			return  $link->trackback;	
		}
		
	}
}

function add_comment ($linkid,$randkey,$author,$content) {
	require_once(mnminclude.'comment.php');
	$comment = new Comment;
	if(strlen($content) > 0){
		$comment->content=$content;
		$comment->link=$linkid;
		$comment->randkey=$randkey;
		$comment->author=$author;
		$comment->store();
		return $comment->id;
	}
	return 0;
}

function add_linkowner($linkid,$ownerid) {
	global $db;
	$sql = "INSERT INTO " . table_link_owner . " (link_id, owner_id, percent) VALUES ($linkid, $ownerid, 100)";
	//die($sql);
	$db->query($sql);
}
	
function trackbackout($type,$link_id,$link_category,$link_trackback,$comment_id=0,$comment_content='') {
	require_once(mnminclude.'user.php');
	
	global $db, $current_user;
	if ($type == 'comment') {
		if ($link_category == get_category_id('人')) {
			//get email addr
			$user_id = $db->get_var('SELECT owner_id FROM ' . table_link_owner . ' WHERE link_id=' . $link_id);
			$user = new User();
			$user->id = $user_id;
			$user->read();
			
			if (($user->email == 'blank@blank.com') || ($user->email == '') || ($user->trackbackout == 'false')) {
				return ;
			}
			
			//check if this user is the submitter and is this is the first comment
			$addvote = false;
			$chksql = "SELECT COUNT(*) FROM " . table_links . " WHERE link_id=" . $link_id . " AND link_author=" . $current_user->user_id;
			$issubmitter = 0;
			$issubmitter = $db->get_var($chksql);
			if ($issubmitter > 0) {
				//check if it the first comment
				$chksql = "SELECT COUNT(*) FROM " . table_comments . " WHERE comment_link_id=" . $link_id . " AND comment_user_id=" . $current_user->user_id;
				$comment_num = 0;
				$comment_num = $db->get_var($chksql);
				if ($comment_num < 2) {
					$addvote = true; //this is the submitter and the first comment
				}
			}
			
			if ($addvote) {
				$subject  = "=?UTF-8?B?".base64_encode($current_user->user_names .'在人物系统中向大家推荐并评价了您')."?="; 
			}
			else {
				$subject  = "=?UTF-8?B?".base64_encode($current_user->user_names .'在人物系统中对您进行了评论')."?="; 
			}
			$headers  = 'MIME-Version: 1.0' . "\r\n"; 
			$headers .= 'Content-type: text/plain; charset=utf-8' . "\r\n"; 
			$headers .= 'To: =?UTF-8?B?' .$user->names. '?= <' . $user->email .'>' . "\r\n"; 
			$headers .= 'From: =?UTF-8?B?' . base64_encode('青铜') . '?=' . ' <forestyaser@163.com>' . "\r\n"; 
			$headers .= 'Reply-To: Admin <forestyaser@163.com>' . "\r\n"; 
			$message .= $user->names . ': ' . "\r\n" . "\r\n";
			if ($addvote) {
				$message .= '  '. $current_user->user_names . '在人物系统中推荐了您，并进行了如下评论：' . "\r\n\r\n" ;
			}
			else {
				$message .= '  '. $current_user->user_names . '在人物系统中对您进行了如下评论：' . "\r\n\r\n" ;
			}
			$message .= '  '. str_replace('\r\n',"\r\n  ",$comment_content) . "\r\n\r\n";
			$message .= '  您可查看或回复此评论 ' . my_base_url . my_pligg_base . '/story.php?id=' . $link_id . '#c' . $comment_id . "\r\n\r\n";
			$message .= '  您也可查看' . $current_user->user_names . '的档案 ' . my_base_url . my_pligg_base . '/user.php?login=' . $current_user->user_login . '&view=profile' . "\r\n\r\n";
			$message .= '  如您不希望继续接收推荐和评论提醒邮件，请进行设置 ' . my_base_url . my_pligg_base . '/profile.php#setotherinfo' . "\r\n\r\n";
			$message .= "\r\n\r\n" . '  人物系统致力于推荐有价值的人和物，欢迎您使用' . "\r\n\r\n";
			$message .= '  有任何疑问请咨询站务 青铜 forestyaser@163.com  谢谢！';
			return mail($user->email, $subject, $message, $headers);
		}
		if ($link_category == get_category_id('物')) {
			require_once(mnminclude.'trackback.php');
			$trackres = new Trackback;
			$trackres->url=trim($link_trackback);
			$trackres->link=$link_id;
			$trackres->title=$current_user->user_names . '在人物系统中添加了如下评论';
			$trackres->author=$current_user->user_id;
			$comment_content=str_replace('\r\n',"\r\n",$comment_content);
			$trackres->content=$comment_content . "\r\n" . "\r\n". '人物系统'  . '推荐有价值的人和物'.' ' .my_base_url . my_pligg_base . '  ';
			$res = $trackres->sendcomment($comment_id);
		}
	}
	if ($type == 'vote') {
		if ($link_category == get_category_id('人')) {

			$link_votes = 0;
			$link_votes = $comment_id + 1;
			//get email addr
			$user_id = $db->get_var('SELECT owner_id FROM ' . table_link_owner . ' WHERE link_id=' . $link_id);
			$user = new User();
			$user->id = $user_id;
			$user->read();
			
			if ((($comment_id == 0) && ($user->first_time == 'true')) || (($user->email == 'blank@blank.com') || ($user->email == '') || ($user->trackbackout == 'false'))) {
				return ;//first time , the user is created by recommendation
			}
			
			$subject  = "=?UTF-8?B?".base64_encode($current_user->user_names .'在人物系统中向大家推荐了您')."?="; 
			$headers  = 'MIME-Version: 1.0' . "\r\n"; 
			$headers .= 'Content-type: text/plain; charset=utf-8' . "\r\n"; 
			$headers .= 'To: =?UTF-8?B?' .$user->names. '?= <' . $user->email .'>' . "\r\n"; 
			$headers .= 'From: =?UTF-8?B?' . base64_encode('青铜') . '?=' . ' <forestyaser@163.com>' . "\r\n"; 
			$headers .= 'Reply-To: Admin <forestyaser@163.com>' . "\r\n"; 
			$message .= $user->names . ': ' . "\r\n" . "\r\n";
			$message .= '  '. $current_user->user_names . '在人物系统中向大家推荐了您. 迄今为止您总共获得了' . $link_votes . '人的推荐.' . "\r\n\r\n" ;
			$message .= '  您可查看所有人对您的推荐和评论 ' . my_base_url . my_pligg_base . '/story.php?id=' . $link_id . "\r\n\r\n";
			$message .= '  您也可查看' . $current_user->user_names . '的档案 ' . my_base_url . my_pligg_base . '/user.php?login=' . $current_user->user_login . '&view=profile' . "\r\n\r\n";
			$message .= '  如您不希望继续接收推荐和评论提醒邮件，请进行设置 ' . my_base_url . my_pligg_base . '/profile.php#setotherinfo' . "\r\n\r\n";
			$message .= "\r\n\r\n" . '  人物系统致力于推荐有价值的人和物，欢迎您使用' . "\r\n\r\n";
			$message .= '  有任何疑问请咨询站务 青铜 forestyaser@163.com  谢谢！';
			return mail($user->email, $subject, $message, $headers);
		}
		if ($link_category == get_category_id('物')) {
			$link_votes = 0;
			$link_votes = $comment_id + 1;
			require_once(mnminclude.'trackback.php');
			$trackres = new Trackback;
			$trackres->url=trim($link_trackback);
			$trackres->link=$link_id;
			$trackres->title=$current_user->user_names . '在人物系统中对此做了推荐';
			$trackres->author=$current_user->user_id;
			$comment_content=$current_user->user_names . '在人物系统中对此做了推荐. 迄今为止总共' . $link_votes . '人对此进行了推荐.';
			$comment_content=str_replace('\r\n',"\r\n",$comment_content);
			$trackres->content=$comment_content . "\r\n" . "\r\n". '人物系统'  . '推荐有价值的人和物'.' ' .my_base_url . my_pligg_base . '  ';
			$res = $trackres->sendcomment(-1);
		}
	}
}
?>
